
//
//  SEGNewDoorManager.m
//  YYKitDemo
//
//  Created by 刘山 on 2017/11/8.
//  Copyright © 2017年 Sam. All rights reserved.
//

#import "SEGNewDoorManager.h"

#if __has_include(<Commom/SEGCommonDoorManager.h>)
#import <Commom/SEGCommonDoorManager.h>
#else
#import "SEGCommonDoorManager.h"
#endif

@implementation SEGNewDoorManager

/**
 * 拉取所有门列表
 *
 * @author Sam
 */
-(void)requestmyDoorListFinished:(SEGRequestCallBack)finished
{
    [[SEGCommonDoorManager sharedManager] requestmyDoorListFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (isSuccessed) {
            NSArray* data = [result valueForKey:@"data"];
            NSMutableArray* arrM = [NSMutableArray arrayWithCapacity:data.count];
            for (NSDictionary* dic in data) {
                SEGNewMyDoorListModel* _model = [SEGNewMyDoorListModel yy_modelWithJSON:dic];
                [arrM addObject:_model];
            }
            self.dataMyDoorListSource = [arrM copy];
            //保存所有门到本地
            [self saveAllDoor];
            //保存并更新常用门
            [self seg_comparCommDoorForAllDoor];
        }
        finished(YES, codeType, errorMessage);
    }];
}

- (void)submitOpenDoorHistory{
    __block NSArray* subHisArr = [[NSUserDefaults standardUserDefaults] arrayForKey:@"subHis"];
    
    if (subHisArr && subHisArr.count > 0) {
        //先删除老版本数据
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:subHisArr];
        NSMutableArray *oldDataArray = [NSMutableArray array];
        [subHisArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            BOOL isOldData = [[obj allKeys] containsObject:@"systemVersion"];//老版本独有字段
            if (isOldData) {
                [oldDataArray addObject:obj];
            }
        }];
        if (oldDataArray.count > 0) {
            [tempArray removeObjectsInArray:oldDataArray];
            [[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:@"subHis"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
        // 上传蓝牙开门次数
        UIDevice *device = [UIDevice currentDevice];
        NSString *appSystemInfo = [NSString stringWithFormat:@"%@ %@",device.systemName, device.systemVersion];
        NSString *appSystemDesc = [NSString stringWithFormat:@" %@, model = %@, device.name = %@", [SEGUtils segDeviceHardWareName] ,device.model, device.name];
        NSDictionary* parmas = @{
                                 @"appType" : @"2", //APP类型：1 android 2 IOS
                                 @"appSystemInfo" : appSystemInfo, //APP系统信息
                                 @"appSystemDesc" : appSystemDesc, //APP系统描述
                                 @"doorList" : tempArray
                                 };
        [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kOpenDoorHis parameters:parmas finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            NSString *code = [result objectForKey:@"code"];
            if ([code isEqualToString:@"0"] || [code isEqualToString:@"-2"]) {//-2是一个特殊判断，防止新老版本数据不同造成异常一直无法上传
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"subHis"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        }];
    }

}

/**
 * 开门失败一键报单接口
 * @author Wendy
 * @param doorId  doorId
 * @param doorIdStr  doorIdStr
 */
/**
 *
 */
- (void)requestSubmitWorkOrderWithDoorId:(NSString *)doorId
                               doorIdStr:(NSString*)doorIdStr
                                finished:(SEGRequestCallBack)finished
{
    NSDictionary* dict = @{
                           @"userId" : kAccountUserID,
                           @"custId" : ValueToString([SEGProfileManager sharedManager].profile.custId),
                           @"doorId" : doorId,
                           @"doorIdStr": doorIdStr,
                           @"appType" : @"2" //APP类型：1 android 2 IOS
                           };
    
    [SEGHTTPBusinessManager seg_requestJSONWithMethod:POST URLString:kSubmitWorkOrder parameters:dict finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        finished(isSuccessed, codeType, errorMessage);
    }];
}

-(NSArray<SEGNewMyDoorListModel *> *)dataMyDoorListSource{
    if (!_dataMyDoorListSource) {
        _dataMyDoorListSource = [NSArray array];
    }
    return _dataMyDoorListSource;
}

- (NSArray<SEGNewMyDoorListModel *> *)dataMyCommonDoorListSource {
    if (!_dataMyCommonDoorListSource) {
        _dataMyCommonDoorListSource = [NSArray array];
    }
    return _dataMyCommonDoorListSource;
}

#pragma mark - 常用门

// 保存常用门
-(void)saveCommonDoor{
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.dataMyCommonDoorListSource];
    [NSKeyedArchiver archiveRootObject:arrM toFile:[SEGNewDoorManager segPathForCommonDoor]];
}

// 获取常用门
-(NSArray<SEGNewMyDoorListModel*> *)getCommonDoor {
    // !!!:  Wendy，2017.12.12, 区分小区
    NSArray <SEGNewMyDoorListModel*>*allDoors = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:[SEGNewDoorManager segPathForCommonDoor]]];
    self.dataMyCommonDoorListSource = [NSMutableArray array];
    NSMutableArray<SEGNewMyDoorListModel *> *tempCommonDoors = [NSMutableArray array];
    //只获取本小区的常用门
    [allDoors enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.communityId isEqualToString:kAccountCommunityID]) {
            [tempCommonDoors addObject:obj];
        }
    }];
    self.dataMyCommonDoorListSource = [tempCommonDoors copy];
    return self.dataMyCommonDoorListSource;
}

// 更新常用门
- (void)updateCommonDoors:(NSArray<SEGNewMyDoorListModel *> *)newCommonDoors {
    self.dataMyCommonDoorListSource = [newCommonDoors copy];
    [self saveCommonDoor];
}

// 获取常用门
-(void)seg_comparCommDoorForAllDoor{
    [self getCommonDoor];
    __block NSMutableArray<SEGNewMyDoorListModel *> *newCommonDoorArray = [NSMutableArray array];
    self.dataMyCommonDoorListSource = [self getCommonDoor];
    // 常用门 比较更新常用门
    // 要保留常用门顺序 所以外层循环遍历常用门
    [self.dataMyCommonDoorListSource enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel * _Nonnull commonDoorModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.dataMyDoorListSource enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel * _Nonnull doorModel, NSUInteger idx1, BOOL * _Nonnull stop1) {
            if ([commonDoorModel.doorId isEqualToString:doorModel.doorId]) {
                [newCommonDoorArray addObject:doorModel];
                *stop1 = YES;
            }
        }];
    }];
    self.dataMyCommonDoorListSource = [newCommonDoorArray copy];
    [self saveCommonDoor];
}

#pragma mark - 所有门
// 获取所有门
-(void)getAllDoorList
{
    NSArray <SEGNewMyDoorListModel*>*allDoors = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:[SEGNewDoorManager segPathForAllDoor]]];
    NSMutableArray *currentDoorList = [NSMutableArray array];
    [allDoors enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.communityId isEqualToString:kAccountCommunityID]) {
            [currentDoorList addObject:obj];//只获取本小区的门
        }
    }];
    
    // ---- 门禁列表排序逻辑 Begin
    // 对新数据和旧数据做处理：取得之前排序的门禁列表，遍历当前列表，拿到下标和doorID组成的字典，根据字典排序
    NSMutableArray *oldSortArray = [NSMutableArray arrayWithArray:[self getSortDoor]];
    NSMutableDictionary *tempDictionary = [NSMutableDictionary dictionary];
    [currentDoorList enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger index = [oldSortArray indexOfObject:obj];
        if (index == NSNotFound) {
            index = oldSortArray.count + idx;
        }
        [tempDictionary setObject:@(index) forKey:obj.doorId];
    }];
    [currentDoorList sortUsingComparator:^NSComparisonResult(SEGNewMyDoorListModel * _Nonnull obj1, SEGNewMyDoorListModel *  _Nonnull obj2) {
        NSInteger index1 = [[tempDictionary objectForKey:obj1.doorId] integerValue];
        NSInteger index2 = [[tempDictionary objectForKey:obj2.doorId] integerValue];
        if (index1 == index2) {
            return NSOrderedSame;
        } else if (index1 < index2) {
            return NSOrderedAscending;
        } else {
            return NSOrderedDescending;
        }
    }];
    // 保存新的排序列表
    [self saveSortDoor:currentDoorList];
    // ---- 门禁列表排序逻辑 End
    
    self.dataMyDoorListSource = currentDoorList;
}

// 保存所有门
-(void)saveAllDoor{
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:self.dataMyDoorListSource];
    [NSKeyedArchiver archiveRootObject:arrM toFile:[SEGNewDoorManager segPathForAllDoor]];
}


#pragma mark - 排序之后的门
/**
 保存排序之后的门

 @param sortDoorList 排序之后的门禁列表
 */
- (void)saveSortDoor:(NSArray<SEGNewMyDoorListModel*> *)sortDoorList {
    [NSKeyedArchiver archiveRootObject:sortDoorList toFile:[SEGNewDoorManager segPathForSortDoor]];
}

// 获取当前小区排序之后的门
- (NSArray<SEGNewMyDoorListModel*> *)getSortDoor {
    NSArray<SEGNewMyDoorListModel*> *sortDoors = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:[SEGNewDoorManager segPathForSortDoor]]];
    NSMutableArray<SEGNewMyDoorListModel*> *tempDoors = [[NSMutableArray alloc] init];
    [sortDoors enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel  *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.communityId isEqualToString:kAccountCommunityID]) {
            //只获取本小区的排序列表
            [tempDoors addObject:obj];
        }
    }];
    return tempDoors;
}

/**
 * 本地常用门保存路径
 * @author Sam
 */
+(NSString*)segPathForCommonDoor{
    SEGProfileModel *account = [SEGProfileManager sharedManager].profile;
    NSString *fileName = [NSString stringWithFormat:@"CommonOpenDoor%@%@.data",ValueToString(account.userId),ValueToString(account.jobCommunity)];
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
}

/**
 * 本地所有门保存路径
 * @author Sam
 */
+(NSString*)segPathForAllDoor{
    SEGProfileModel *account = [SEGProfileManager sharedManager].profile;
    NSString *fileName = [NSString stringWithFormat:@"AllOpenDoor%@%@.data",ValueToString(account.userId),ValueToString(account.jobCommunity)];
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
}


/**
 @return 本地当前社区对应的排序之后的门禁保存路径
 */
+ (NSString *)segPathForSortDoor {
    SEGProfileModel *account = [SEGProfileManager sharedManager].profile;
    NSString *fileName = [NSString stringWithFormat:@"SortOpenDoor%@%@.data",ValueToString(account.userId),ValueToString(account.jobCommunity)];
    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:fileName];
}

@end
